<template>
  <!-- 配置菜单权限 -->
  <el-drawer v-model="permParams.visible" :title="'权限分配'" @open="handleOpen" size="500" :close-on-click-modal="false">
    <div class="drawer-main">
      <div class="drawer-header">
        <el-input v-model="keywords" clearable placeholder="菜单权限名称">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" plain @click="togglePermTree" icon="Switch" class="ml20">
          {{ isExpanded ? "收缩" : "展开" }}
        </el-button>
      </div>
      <el-scrollbar v-loading="loading">
        <el-tree ref="permTreeRef" node-key="id" show-checkbox :props="defaultProps" :data="permOptions"
          :filter-node-method="filterNode" :default-expand-all="true" :check-strictly="false" />
      </el-scrollbar>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emit('close')">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getMenuTree } from '@views/menuManage/api/menuManage'
import { assignRoleMenu } from '@views/roleManage/api/roleManage'
const props = defineProps({
  permParams: {
    type: Object,
    default: () => { },
    required: true
  }
})

const loading = ref(false)
const keywords = ref('')
// const defaultProps = { label: 'name', value: 'id', disabled: data => !data.status }
const defaultProps = { label: 'name', value: 'id' }
const isExpanded = ref(true)
const permTreeRef = ref(null)
const permOptions = ref([])
const emit = defineEmits(['close'])

// 权限筛选
watch(keywords, (val) => {
  permTreeRef.value.filter(val)
})

const handleSave = async () => {
  const checkedMenuIds = permTreeRef.value.getCheckedNodes(false, true)
    .map((node) => node.id)
  loading.value = true
  const res = await assignRoleMenu(props.permParams.row.roleId, checkedMenuIds)
  loading.value = false
  if (res?.code === 200) {
    ElMessage.success('保存成功')
    emit('close', true)
  }
}

// 展开/收缩 菜单权限树
const togglePermTree = () => {
  isExpanded.value = !isExpanded.value
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node) => {
      if (isExpanded.value) {
        node.expand()
      } else {
        node.collapse()
      }
    })
  }
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 获取数据
const getMenuData = async () => {
  loading.value = true
  const res = await getMenuTree({})
  loading.value = false
  if (res?.code === 200) {
    permOptions.value = res.data || []
    nextTick(() => {
      console.log(props.permParams.row.menuIds)
      const checkedMenuIds = props.permParams.row.menuIds || []
      checkedMenuIds.forEach((menuId) => {
        console.log(menuId)
        permTreeRef.value.setChecked(menuId, true, false)
      })
    })
  }
}

// 初始化弹窗
const handleOpen = () => {
  getMenuData()

  nextTick(() => {
    permTreeRef.value.setCheckedKeys([]) // 清空选中节点
    console.log('初始化')
  })
}

</script>

<style lang="scss" scoped>
.drawer-main {
  height: 100%;
  display: flex;
  flex-direction: column;

  .drawer-header {
    display: flex;
    margin-bottom: 20px;
  }
}
</style>
